package com.michaelbulava.TFS.ui.framework.validation;

import com.microsoft.tfs.util.valid.AbstractValidator;
import com.microsoft.tfs.util.valid.IValidity;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

/**
 * Created by mbulava on 6/15/2015.
 */
public abstract class AbstractTextControlValidator extends AbstractValidator {

    private final DocumentListener modifyListener = new DocumentListener() {
        @Override
        public void insertUpdate(DocumentEvent e) {
            validate();
        }

        @Override
        public void removeUpdate(DocumentEvent e) {
            validate();
        }

        @Override
        public void changedUpdate(DocumentEvent e) {
            validate();
        }

    };

    protected AbstractTextControlValidator(JTextField subject){
        super(subject);
        getTextControlSubject().getDocument().addDocumentListener(modifyListener);
    }

    public final JTextField getTextControlSubject(){
        return (JTextField)getSubject();
    }

    public void dispose(){
        JTextField subject = getTextControlSubject();
        subject.getDocument().removeDocumentListener(modifyListener);
    }

    protected void onTextModified(){
        JTextField subject = getTextControlSubject();
        validate(subject.getText());
    }

    protected void validate(){
        JTextField subject = getTextControlSubject();
        validate(subject.getText());
    }

    protected void validate(String text){
        IValidity validity = computeValidity(text);
        setValidity(validity);
    }

    protected abstract IValidity computeValidity(String paramString);



}
